package com.acooly.module.openapi.client.provider.bosc;

import com.acooly.module.openapi.client.api.notify.ApiServiceClientServlet;
import com.acooly.module.openapi.client.api.transport.HttpTransport;
import com.acooly.module.openapi.client.api.transport.Transport;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

import static com.acooly.module.openapi.client.provider.bosc.OpenAPIClientBoscProperties.PREFIX;


@EnableConfigurationProperties({OpenAPIClientBoscProperties.class})
@ConditionalOnProperty(value = PREFIX + ".enable", matchIfMissing = true)
@ComponentScan
public class OpenAPIClientBoscConfigration {

    @Autowired
    private OpenAPIClientBoscProperties openAPIClientBoscProperties;

    @Bean("boscHttpTransport")
    public Transport fuiouHttpTransport() {
        HttpTransport httpTransport = new HttpTransport();
        httpTransport.setGateway(openAPIClientBoscProperties.getGatewayUrl());
        httpTransport.setConnTimeout(String.valueOf(openAPIClientBoscProperties.getConnTimeout()));
        httpTransport.setReadTimeout(String.valueOf(openAPIClientBoscProperties.getReadTimeout()));
        return httpTransport;
    }

    /**
     * 接受异步通知的servlet
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean boscApiServiceClientServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setUrlMappings(Lists.newArrayList(openAPIClientBoscProperties.getNotifyUrl()));
        ApiServiceClientServlet apiServiceClientServlet = new ApiServiceClientServlet();
        bean.setServlet(apiServiceClientServlet);
        bean.addInitParameter(ApiServiceClientServlet.NOTIFY_DISPATCHER_BEAN_NAME_KEY, "boscNotifyHandlerDispatcher");
        return bean;
    }

}
